package com.redstar.HappyRefresh.authority;

import org.springframework.util.ObjectUtils;

import java.util.*;

public class AuthorityUtils {

    private static final Map<Long, Collection<String>> permissionMap = new HashMap<>(); // 权限集合

    private static Class c; // 全局权限校验类

    private static Boolean globalVerify = false; // 是否开启全局校验

    public static Boolean isGlobalVerify() { // 重新初始化全局校验类Class
        return globalVerify;
    }

    public static Class getGlobalVerify() { // 获取全局权限校验类
        return c;
    }

    public static void setGlobalVerify(Boolean state, Object object) { // 开启全局校验
        if (object == null) {
            throw new RuntimeException("全觉校验对象为null");
        } else if (!(object instanceof AuthorityVerify)) {
            throw new RuntimeException(object.getClass() + "类型不是AuthorityVerify的实现类");
        }
        c = object.getClass();
        globalVerify = state;
    }

    public static void setAuthority(Long uId, Collection<String> authority) { // 保存用户权限对应的操作
        permissionMap.put(uId, authority);
    }

    public static Boolean verify(Long uId, String authority) { // 校验权限
        if (isEmpty(uId)) {
            return false;
        }
        return permissionMap.get(uId).contains(authority);
    }

    public static Boolean isEmpty(Long uId) { // uId对应的权限是否为null
        return ObjectUtils.isEmpty(permissionMap.get(uId));
    }

}
